import React, {
  ReactElement,
  useContext,
  useEffect,
  useMemo,
  useState
} from 'react';
import {
  GestureResponderEvent,
  Image,
  PanResponder,
  Text,
  View,
  UIManager,
  LayoutAnimation,
  Vibration
} from 'react-native';
import { AudioRecorder } from 'react-native-audio';
import RNFS from 'react-native-fs';

import Mask from '../../../../../../components/Mask';
import { isIOS } from '../../../../../../constant';

import {
  deleteRecord,
  deleteRecordGray,
  record
} from '../../../../../../constant/resource';
import { phonePx } from '../../../../../../util/adapt';
import {
  getScreenInfo,
  ScreenOrientation
} from '../../../../../../util/screen';
import { CLASS_ROOM_RIGHT_SCALE, MARGIN_TOP } from '../../../../constant';

import Ripple from '../Ripple';
import SendMsg from '../../../Graph/SendMsg';
import styles from './style';
import { getAudioPreUploadInfo, recordScrollToEnd } from '../../actions';
import {
  mutePPT,
  pausePPT,
  playPPT,
  recordUpdateAudioAvailable
} from '../../../../actions';
import { Store } from '../../reducer';
import { toolTipOpen } from '../../../../../../util/global';

if (!isIOS) {
  if (UIManager.setLayoutAnimationEnabledExperimental) {
    UIManager.setLayoutAnimationEnabledExperimental(true);
  }
}

const { height } = getScreenInfo({
  screenOrientation: ScreenOrientation.Landscape
});

export const audioPath = `${
  isIOS ? RNFS.DocumentDirectoryPath : RNFS.ExternalDirectoryPath
}/videos/test.aac`;

export default (): ReactElement => {
  const [cannel, setCannel] = useState(false);
  const [isCannelDesc, setIsCannelDesc] = useState(false);
  const [showRecording, setShowRecording] = useState(false);
  const [duration, setDuration] = useState(0);

  const { state } = useContext(Store);
  const { isVod } = state;

  useEffect((): void => {
    AudioRecorder.onProgress = (data): void => {
      setDuration(data.currentTime);
    };
  }, []);

  const startRecord = (): void => {
    recordScrollToEnd();
    mutePPT(true);
    recordUpdateAudioAvailable(false);
    AudioRecorder.prepareRecordingAtPath(audioPath, {
      SampleRate: 22050,
      Channels: 1,
      AudioQuality: 'High',
      AudioEncoding: 'aac'
    });
    AudioRecorder.startRecording();
  };

  const startSendRecord = async (): Promise<void> => {
    try {
      await AudioRecorder.stopRecording();
    } catch (error) {
      toolTipOpen({ desc: '说话时间太短' });
    }
    mutePPT(false);
    recordUpdateAudioAvailable(true);
    if (isIOS) {
      await pausePPT();
      setTimeout((): void => {
        playPPT();
      });
    }
    if (cannel) return;

    if (duration < 1) {
      toolTipOpen({ desc: '说话时间太短' });
      RNFS.unlink(audioPath);
      return;
    }

    getAudioPreUploadInfo(audioPath, duration);
    setDuration(0);
  };

  const responder = PanResponder.create({
    onPanResponderTerminationRequest: (): boolean => !isVod,
    onStartShouldSetPanResponder: (): boolean => !isVod,
    onMoveShouldSetPanResponder: (): boolean => !isVod,
    onPanResponderEnd: (): void => {
      setShowRecording(false);
      startSendRecord();
      setCannel(false);
      setIsCannelDesc(false);
    },
    onPanResponderGrant: (evt): void => {},
    onPanResponderMove: (evt: GestureResponderEvent): void => {
      if (
        evt.nativeEvent.pageY >
        height - phonePx(46) * CLASS_ROOM_RIGHT_SCALE - MARGIN_TOP
      ) {
        setIsCannelDesc(false);
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        setCannel(false);
      } else {
        setIsCannelDesc(true);
        LayoutAnimation.configureNext(LayoutAnimation.Presets.easeInEaseOut);
        setCannel(true);
      }
    },
    onPanResponderStart: (): void => {
      if (showRecording) return;
      setShowRecording(true);
      Vibration.vibrate(100, false);
      startRecord();
    }
  });

  return useMemo(
    (): ReactElement => (
      <View style={styles.container} {...responder.panHandlers}>
        <View style={styles.speakContent}>
          <View style={[styles.speak, isVod ? styles.vodSpeak : {}]}>
            <Text style={[styles.desc, isVod ? styles.vodDesc : {}]}>
              {isVod ? '回放状态不能发言' : '按住说话'}
            </Text>
          </View>
        </View>
        {showRecording && (
          <Mask style={styles.content} resAlpha={0.8}>
            <SendMsg
              style={[styles.send, cannel ? styles.cancelSend : {}]}
              fillColor={cannel ? '#313131' : '#D8D8D8'}
            >
              <Image
                source={record}
                style={[styles.record, cannel ? styles.cannelRecord : {}]}
              />
            </SendMsg>
            <Ripple
              fillColor={cannel ? '#FA5151' : '#FDD753'}
              lineColor={cannel ? '#AF6262' : '#B5A777'}
            />
            <View style={[styles.statusContent, styles.cannelStatus]}>
              <Image
                source={cannel ? deleteRecord : deleteRecordGray}
                style={cannel ? styles.cannelStatus : styles.sendStatus}
              />
            </View>
            {isCannelDesc ? (
              <Text style={styles.cannelDesc}>松开取消</Text>
            ) : (
              <Text style={styles.sendDesc}>松开发送</Text>
            )}
          </Mask>
        )}
      </View>
    ),
    [cannel, isCannelDesc, isVod, responder.panHandlers, showRecording]
  );
};
